package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.ImagePickerTwoAdapter;
import com.dlwx.firefighting.bean.UserBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.DealResult;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.ImagePickerUtil;
import com.dlwx.firefighting.utils.KeyBoardUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.widget.CircleImageView;
import com.dlwx.firefighting.widget.SelectDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 用户资料界面
 */
public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.info_edit_name)
    EditText edit_name;
    @BindView(R.id.title_right_one_tv)
    TextView titleRightOneTv;
    @BindView(R.id.info_edit_phone)
    EditText edit_phone;
    @BindView(R.id.info_edit_blankcard)
    EditText editBlank;
    @BindView(R.id.img_header)
    CircleImageView imgHeader;
    @BindView(R.id.header_rl)
    RelativeLayout headerRl;
    @BindView(R.id.info_edit_idcard)
    EditText infoEditIdcard;
    @BindView(R.id.tv_content)
    TextView tvContent;

    private String userName;
    private String userPhone;
    private String userBlank;
    private String userId;
    //
    private ImagePickerTwoAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 1;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    ArrayList<ImageItem> images = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        userId = (String) SPUtils.get(this, Constant.USER_ID, "");
        initView();
        getDatas();
        ImagePickerUtil.init();
    }

    private void getDatas() {

        OkGo.<String>post(Constant.USER)
                .tag(this)
                .params("user_id", userId)
                .params("action", "user_info")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<UserBean> beans = dealResult.deal(UserInfoActivity.this, response, new TypeToken<BaseBean<UserBean>>() {
//                        }.getType());
//                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(UserInfoActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<UserBean> beans) {
        if (beans.isEmpty()) {
            return;
        }
        tvContent.setText(beans.get(0).getFuli());
        edit_name.setText(beans.get(0).getUser_name());
        Glide.with(UserInfoActivity.this).load(beans.get(0).getHeadimg()).error(R.mipmap.error_small1).into(imgHeader);

    }

    private void initView() {
        selImageList = new ArrayList<>();
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText(getResources().getString(R.string.my_info));
        /*titleRightOneTv.setVisibility(View.VISIBLE);
        titleRightOneTv.setText(getResources().getString(R.string.update));*/

        //从缓存中取出已经保存的信息

        userPhone = (String) SPUtils.get(this, Constant.userPhone, "");
        edit_phone.setText(userPhone);
        userBlank = (String) SPUtils.get(this, Constant.userBlankCard, "");
        editBlank.setText(userBlank);

    }

    @OnClick({R.id.title_left_one_btn, R.id.title_right_one_tv, R.id.info_edit_idcard, R.id.header_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.title_right_one_tv:
                changeState();
                break;
            case R.id.header_rl:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(1);

                                Intent intent = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(1);
                                ImagePicker.getInstance().setCrop(true);        //允许裁剪（单选才有效）
                                ImagePicker.getInstance().setSaveRectangle(false); //是否按矩形区域保存
                                ImagePicker.getInstance().setSelectLimit(1);    //选中数量限制
                                ImagePicker.getInstance().setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
                                ImagePicker.getInstance().setFocusWidth(600);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                                ImagePicker.getInstance().setFocusHeight(600);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                                ImagePicker.getInstance().setOutPutX(200);//保存文件的宽度。单位像素
                                ImagePicker.getInstance().setOutPutY(200);//保存文件的高度。单位像素
                                Intent intent1 = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
        }
    }

    /**
     * 底部弹出选择拍照还是图库
     */
    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style.transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    /**
     * 修改和保存状态切换
     */
    private void changeState() {
        if (TextUtils.equals("修改", titleRightOneTv.getText().toString())) {
            titleRightOneTv.setText("保存");
            edit_name.setEnabled(true);
            edit_name.setClickable(true);
            edit_name.setCursorVisible(true);

            edit_phone.setEnabled(true);
            edit_phone.setClickable(true);

            editBlank.setEnabled(true);
            editBlank.setClickable(true);
        } else if (TextUtils.equals("保存", titleRightOneTv.getText().toString())) {
            //关闭软键盘
            KeyBoardUtils.closeKeybord(UserInfoActivity.this);
            DialogUtils.stopProgressDlg();
            //设置不可编辑
            edit_name.setEnabled(false);
            edit_name.setClickable(false);
            edit_name.setCursorVisible(false);

            edit_phone.setEnabled(false);
            edit_phone.setClickable(false);

            editBlank.setEnabled(false);
            editBlank.setClickable(false);
            saveUserInfo(edit_name.getText().toString(), edit_phone.getText().toString(), editBlank.getText().toString());
        }
    }

    private void saveUserInfo(final String userName, final String phone, final String bankNum) {
        OkGo.<String>post(Constant.USER)
                .tag(this)
                .params("user_id", userId)
                .params("action", "user_info_edit")
                .params("user_name", userName)
                .params("mobile_phone", phone)
                .params("bank_card_number", bankNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        BaseBean bean = dealResult.dealBaseRes(UserInfoActivity.this, response);
//                        if (bean != null) {
//                            if (bean.getStatus() == Constant.SUCESS) {
//                                SPUtils.put(UserInfoActivity.this, Constant.userName, userName);
//                                SPUtils.put(UserInfoActivity.this, Constant.userPhone, phone);
//                                SPUtils.put(UserInfoActivity.this, Constant.userBlankCard, bankNum);
//                                ToastUtils.toastForShort(UserInfoActivity.this, bean.getMsg());
//                                UserInfoActivity.this.finish();
//                            } else {
//                                ToastUtils.toastForShort(UserInfoActivity.this, bean.getMsg());
//                            }
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(UserInfoActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    Glide.with(UserInfoActivity.this).load(images.get(0).path).into(imgHeader);
                    updateHeadImg(images.get(0).path);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    Glide.with(UserInfoActivity.this).load(images.get(0).path).into(imgHeader);
                    /*selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);*/
                }
            }
        }
    }

    private void updateHeadImg(String path) {
        OkGo.<String>post(Constant.USER)
                .tag(this)
                .params("user_id", userId)
                .params("action", "avatar_edit")
                .params("headimg", new File(path))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DealResult dealResult = new DealResult();
                       /* BaseBean bean = dealResult.dealBaseRes(UserInfoActivity.this, response);
                        if (bean != null) {
                            if (bean.getStatus() == Constant.SUCESS) {
                                SPUtils.put(UserInfoActivity.this, Constant.userName, userName);
                                SPUtils.put(UserInfoActivity.this, Constant.userPhone, phone);
                                SPUtils.put(UserInfoActivity.this, Constant.userBlankCard, bankNum);
                                ToastUtils.toastForShort(UserInfoActivity.this, bean.getMsg());
                                UserInfoActivity.this.finish();
                            } else {
                                ToastUtils.toastForShort(UserInfoActivity.this, bean.getMsg());
                            }
                        }*/
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(UserInfoActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    //--------------------------------------------------------
}
